<!DOCTYPE html>
<html lang="en">
  <head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
  <meta content="" name="keywords">

  <title> 杂技浅尝 - </title>
  <meta name="description" content="" />
  <meta property="og:title" content="杂技浅尝" />
  <meta name="twitter:title" content="杂技浅尝" />
  <meta name="author" content="{Description { .Site.Author.name }}"/>
  <meta name="twitter:card" content="summary" />
  <meta property="og:url" content="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/" />
  <meta property="og:type" content="website" />
  <meta property="og:site_name" content="听风的小站" />

  <meta name="generator" content="Hugo 0.67.0" />
  <link rel="canonical" href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/" />
  <link rel="alternate" href="https://systemime.github.io/index.xml" type="application/rss+xml" title="听风的小站">
  <script src="https://res.cloudinary.com/jimmysong/raw/upload/rootsongjc-hugo/jquery-1.12.4.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.css" integrity="sha384-wITovz90syo1dJWVh32uuETPVEtGigN07tkttEqPv+uR2SE/mbQcG7ATL28aI9H0" crossorigin="anonymous">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  
  
  <link rel="stylesheet" href="https://systemime.github.io/css/main.css" />
  <link rel="stylesheet" href="https://systemime.github.io/css/my.css" />
  <link rel="stylesheet" href="https://systemime.github.io/css/pace.css" />
  <link rel="stylesheet" href="https://cdn.plyr.io/3.4.7/plyr.css">
  <link rel="stylesheet" href="https://systemime.github.io/css/lightgallery.css" />
  <link rel="stylesheet" href="https://systemime.github.io/css/baguetteBox.css" />
  <link rel="stylesheet" href="https://systemime.github.io/css/search.css" />
  <link rel="stylesheet" href="https://systemime.github.io/css/reward.css" />
  <link rel="stylesheet" href="https://systemime.github.io/css/share.min.css" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" />
  <link rel="stylesheet" href="https://systemime.github.io/css/pygment_highlights.css" />
  <link rel="stylesheet" href="https://systemime.github.io/css/highlight.min.css" />
  <link rel="stylesheet" href="https://systemime.github.io/css/toc.css" />
  <link rel="stylesheet" href="https://systemime.github.io/css/lightbox.css" />
  <link rel="stylesheet" href="https://systemime.github.io/live2d/css/live2d.css" />
  
  <link href="https://systemime.github.io/css/video-js.css" rel="stylesheet">


<meta name="baidu-site-verification" content="g8IYR9SNLF" />
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?cffe439e37449bb1c07ab26ab56484bb";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>

<link rel="stylesheet" href="https://systemime.github.io/css/prism.css" />









<script src="https://systemime.github.io/js/pace.min.js" data-no-instant></script>



<script src="https://systemime.github.io/js/instantclick.min.js" data-no-instant></script>
   <script data-no-instant>
   InstantClick.on('change', function(isInitialLoad) {
     if (isInitialLoad === false) {
       if (typeof MathJax !== 'undefined') 
         MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
       if (typeof prettyPrint !== 'undefined') 
         prettyPrint();
       if (typeof _hmt !== 'undefined')  
         _hmt.push(['_trackPageview', location.pathname + location.search]);
       if (typeof ga !== 'undefined')  
           ga('send', 'pageview', location.pathname + location.search);
     }
   });
   InstantClick.init();
</script>




<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/gist-embed/2.7.1/gist-embed.min.js"></script>


<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
  (adsbygoogle = window.adsbygoogle || []).push({
    google_ad_client: "ca-pub-3925981084585036",
    enable_page_level_ads: true
  });
</script>



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.1/photoswipe.min.css" integrity="sha256-sCl5PUOGMLfFYctzDW3MtRib0ctyUvI9Qsmq2wXOeBY=" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.1/default-skin/default-skin.min.css" integrity="sha256-BFeI1V+Vh1Rk37wswuOYn5lsTcaU96hGaI7OUVCLjPc=" crossorigin="anonymous" />



<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

<div class="pswp__bg"></div>

<div class="pswp__scroll-wrap">
    
    <div class="pswp__container">
      <div class="pswp__item"></div>
      <div class="pswp__item"></div>
      <div class="pswp__item"></div>
    </div>
    
    <div class="pswp__ui pswp__ui--hidden">
    <div class="pswp__top-bar">
      
      <div class="pswp__counter"></div>
      <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
      <button class="pswp__button pswp__button--share" title="Share"></button>
      <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
      <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
      
      
      <div class="pswp__preloader">
        <div class="pswp__preloader__icn">
          <div class="pswp__preloader__cut">
            <div class="pswp__preloader__donut"></div>
          </div>
        </div>
      </div>
    </div>
    <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
      <div class="pswp__share-tooltip"></div>
    </div>
    <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
    </button>
    <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
    </button>
    <div class="pswp__caption">
      <div class="pswp__caption__center"></div>
    </div>
    </div>
    </div>
</div>

</head>

  <body>
    <nav class="navbar navbar-default navbar-fixed-top navbar-custom">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-navbar">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="https://systemime.github.io">听风的小站</a>
    </div>
    <div class="collapse navbar-collapse" id="main-navbar">
      <ul class="nav navbar-nav navbar-right">
        
          
            <li>
		    <a title="博客" href="https://systemime.github.io/blog/">博客</a>
              
              
            </li>
          
        
          
            <li>
		    <a title="片刻" href="https://systemime.github.io/moment/">片刻</a>
              
              
            </li>
          
        
          
            <li>
		    <a title="关于" href="https://systemime.github.io/about/">关于</a>
              
              
            </li>
          
        
          
            <li>
		    <a title="留言" href="https://systemime.github.io/message/">留言</a>
              
              
            </li>
          
        

        

        
        
      </ul>
    </div>

    <div class="avatar-container">
      <div class="avatar-img-border">
        
      </div>
    </div>

  </div>
</nav>






    
  <header class="header-section ">
    <div class="intro-header no-img">
      <div class="container">
        <div class="row">
          <div class="col-lg-12 col-md-12 col-md-offset-0">
            <div class="page-heading">
              <h1>#杂技浅尝</h1>
              <hr class="small">
            </div>
          </div>
        </div>
      </div>
    </div>
  </header>

    
  <div class="container" role="main">
    <div class="row">
      <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
        
        <div class="posts-list">
          
            <article class="post-preview">
              <a href="https://systemime.github.io/blog/2019-04/python%E5%88%97%E8%A1%A8%E8%A7%A3%E6%9E%90%E5%BC%8F/">
                <h2 class="post-title">Python列表解析式</h2>

                
              </a>

              <p class="post-meta">
                Posted on April 6, 2019
              </p>
              <div class="post-entry">
                
                  <p>照例先是官方文档：<a href="https://docs.python.org/zh-cn/3/tutorial/datastructures.html#tut-listcomps">python列表解析(推导式)</a></p>
<p>原文链接: <a href="http://codingpy.com/article/python-list-comprehensions-explained-visually/">轻松学会Python列表解析式</a></p>
<p>还有一个：<a href="http://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/">原文</a></p>
<h2 id="什么是列表解析式">什么是列表解析式？</h2>
<p>列表解析式是将一个列表（实际上适用于任何<a href="https://docs.python.org/3/glossary.html#term-iterable">可迭代对象（iterable）</a>）转换成另一个列表的工具。在转换过程中，可以指定元素必须符合一定的条件，才能添加至新的列表中，这样每个元素都可以按需要进行转换。</p>
<p>如果你熟悉函数式编程（functional programming），你可以把列表解析式看作为结合了 <code>filter</code> 函数与 <code>map</code> 函数功能的语法糖：</p>
<blockquote>
<p>doubled_odds = map(lambda n: n * 2, filter(lambda n: n % 2 == 1, numbers))
doubled_odds = [n * 2 for n in numbers if n % 2 == 1]</p>
</blockquote>
<p>如果你不熟悉函数式编程，也不用担心：我稍后会通过<code>for</code>循环为大家讲解。</p>
<h2 id="从循环到解析式">从循环到解析式</h2>
<p>每个列表解析式都可以重写为for循环，但不是每个for循环都能重写为列表解析式。</p>
<p>掌握列表解析式使用时机的关键，在于不断练习识别那些看上去像列表解析式的问题（practice identifying problems that smell like list comprehensions）。</p>
<p>如果你能将自己的代码改写成类似下面这个for循环的形式，那么你也就可以将其改写为列表解析式：</p>
<pre><code>new_things = []
for ITEM in old_things:
    if condition_based_on(ITEM):
        new_things.append(&quot;something with &quot; + ITEM)
</code></pre><p>你可以将上面的for循环改写成这样的列表解析式：</p>
<pre><code>new_things = [&quot;something with &quot; + ITEM for ITEM in old_things if condition_based_on(ITEM)]
</code></pre><h2 id="列表解析式可视化解读">列表解析式：可视化解读</h2>
<p>可视化解读听上去是个不错的注意，但是我们怎么才能做到这点呢？</p>
<p>嘿嘿，只需要从for循环中复制粘贴，稍微调整一下就变成了列表解析式啦。
<img src="https://github.com/systemime/my_image/blob/master/python%E5%88%97%E8%A1%A8%E8%A7%A3%E6%9E%90%E5%BC%8F/D1.gif?raw=true" alt="动图1">
下面是我们复制粘贴的顺序：</p>
<ul>
<li>将变量赋值操作复制到新建的空列表中（第三行）</li>
<li>将<code>append()</code>方法中的表达式参数复制到新列表中（第六行）</li>
<li>复制<code>for</code>循环语句，不包括最后的:（第四行）</li>
<li>复制<code>if</code>条件控制语句，同样不包括最后的:（第五行）</li>
</ul>
<p>这样，我们将从下面这段代码：</p>
<pre><code>numbers = [1, 2, 3, 4, 5]

doubled_odds = []
for n in numbers:
    if n % 2 == 1:
        doubled_odds.append(n * 2)
</code></pre><p>转换成了这两行代码：</p>
<pre><code>numbers = [1, 2, 3, 4, 5]

doubled_odds = [n * 2 for n in numbers if n % 2 == 1]
</code></pre><h2 id="无条件子句的列表解析式">无条件子句的列表解析式</h2>
<p>如果是那些没有条件子句（即 <code>if SOMETHING</code> 部分）的代码呢，又该怎样复制粘贴？这些形式的代码甚至比有条件子句的代码更好实现。</p>
<p>一个没有<code>if</code>语句的<code>for</code>循环：</p>
<pre><code>doubled_numbers = []
for n in numbers:
    doubled_numbers.append(n * 2)
</code></pre><p>上面这段代码页可以改写为一个列表解析式：</p>
<pre><code>doubled_numbers = [n * 2 for n in numbers]
</code></pre><p>下面是转换过程的详细演示：
<img src="https://github.com/systemime/my_image/blob/master/python%E5%88%97%E8%A1%A8%E8%A7%A3%E6%9E%90%E5%BC%8F/D2.gif?raw=true" alt="动图2">
我们可以从上面那个简单的for循环中，安装这样的顺序复制粘贴：</p>
<ul>
<li>将变量赋值操作复制到新建的空列表中（第三行）</li>
<li>将<code>append()</code>方法中的表达式参数复制到新列表中（第五行）</li>
<li>复制for循环语句，不包括最后的:（第四行）</li>
</ul>
<h2 id="嵌套循环">嵌套循环</h2>
<p>那么嵌套循环（nested loop）又该怎样改写为列表解析式呢？</p>
<p>下面是一个拉平（flatten）矩阵（以列表为元素的列表）的for循环：</p>
<pre><code>flattened = []
for row in matrix:
    for n in row:
        flattened.append(n)
</code></pre><p>下面这个列表解析式实现了相同的功能：</p>
<pre><code>flattened = [n for row in matrix for n in row]
</code></pre><p>列表解析式中的嵌套循环读起来就有点绕口了。</p>
<p>注意：我本能地会想把这个列表解析式写成这样：</p>
<pre><code>flattened = [n for n in row for row in matrix]
</code></pre><p>但是这行代码是错误的。这里我不小心颠倒了两个<code>for</code>循环的顺序。正确的代码是之前那个。</p>
<p>如果要在列表解析式中处理嵌套循环，请记住** <code>for</code>循环子句的顺序与我们原来<code>for</code>循环的顺序是一致的**。</p>
<p>同样地原则也适用集合解析式（set comprehension）和字典解析式（dictionary comprehension）。</p>
<h2 id="其他解析式">其他解析式</h2>
<p>下面的代码提取单词序列中每个单词的首字母，创建了一个集合（set）：</p>
<pre><code>first_letters = set()
for w in words:
    first_letters.add(w[0])
</code></pre><p>同样的代码可以改写为集合解析式：</p>
<pre><code>first_letters = {w[0] for w in words}
</code></pre><p>下面的代码将原有字典的键和值互换，从而创建了一个新的字典：</p>
<pre><code>flipped = {}
for key, value in original.items():
    flipped[value] = key
</code></pre><p>同样的代码可以改写为字典解析式：</p>
<pre><code>flipped = {value: key for key, value in original.items()}
</code></pre><h2 id="还要注意可读性">还要注意可读性</h2>
<p>你有没有发现上面的列表解析式读起来很困难？我经常发现，如果较长的列表解析式写成一行代码，那么阅读起来就非常困难。</p>
<p>不过，还好Python支持在括号和花括号之间断行。</p>
<p><strong>列表解析式 List comprehension</strong>
断行前：</p>
<pre><code>doubled_odds = [n * 2 for n in numbers if n % 2 == 1]
</code></pre><p>断行后：</p>
<pre><code>doubled_odds = [
    n * 2
    for n in numbers
    if n % 2 == 1
]
</code></pre><p>** 带嵌套循环的列表解析式 **
断行前：</p>
<pre><code>flattened = [n for n in row for row in matrix]
</code></pre><p>断行后：</p>
<pre><code>flattened = [
    n
    for row in matrix
    for n in row
]
</code></pre><p>** 字典解析式 **
断行前：</p>
<pre><code>flipped = {value: key for key, value in original.items()}
</code></pre><p>断行后：</p>
<pre><code>flipped = {
    value: key
    for key, value in original.items()
}
</code></pre><p>请注意，我们并不是随意进行断行：我们是在每一行复制过来的代码之后断行的。</p>
<h2 id="总结">总结</h2>
<p>纠结于写不出列表解析式吗？不要担心。先写一个for循环，能后按照本文说的顺序复制粘贴，就可以写出解析式了。</p>
<p>任何类似下面代码形式的for循环：</p>
<pre><code>new_things = []
for ITEM in old_things:
    if condition_based_on(ITEM):
        new_things.append(&quot;something with &quot; + ITEM)
</code></pre><p>都可以被改写为下面这种列表解析式：</p>
<pre><code>new_things = [&quot;something with &quot; + ITEM for ITEM in old_things if condition_based_on(ITEM)]
</code></pre>
                
              </div>

              
                <span class="post-meta">
                  
                    #<a href="https://systemime.github.iotags/python/">Python</a>&nbsp;
                  
                    #<a href="https://systemime.github.iotags/%E5%88%97%E8%A1%A8%E8%A7%A3%E6%9E%90/">列表解析</a>&nbsp;
                  
                </span>
              

            </article>
          
            <article class="post-preview">
              <a href="https://systemime.github.io/blog/2019-04/django%E5%AE%9E%E7%8E%B0%E7%AE%80%E5%8D%95%E7%BD%91%E9%A1%B5%E5%BC%B9%E5%87%BA%E8%AD%A6%E5%91%8A/">
                <h2 class="post-title">Django实现简单网页弹出警告</h2>

                
              </a>

              <p class="post-meta">
                Posted on April 6, 2019
              </p>
              <div class="post-entry">
                
                  <h2 id="功能所在位置">功能所在位置</h2>
<p>该功能运用了django.contrib.messages这个库，再django项目中srtting.py文件中的38行，APP注册部分</p>
<pre><code>INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',  # 自定义APP注册
]
</code></pre><h2 id="导入库">导入库</h2>
<pre><code>from django.contrib import messages

def abc(request):
    messages.success(request, &quot;哈哈哈&quot;)
</code></pre><h2 id="前台代码添加">前台代码添加</h2>
<p>需在html页面上显示这个消息提示框，代码如下，但必须注意的是如果页面有多个表单的时候，只需要在表单结束后加一次就够了，view底下不同的函数可以显示不同的消息：</p>
<pre><code>{% if messages %}
    &lt;script&gt;
        {% for msg in messages %}
            alert('{{ msg.message }}');
        {% endfor %}
    &lt;/script&gt;
{% endif %}
</code></pre>
                
              </div>

              
                <span class="post-meta">
                  
                    #<a href="https://systemime.github.iotags/django/">Django</a>&nbsp;
                  
                    #<a href="https://systemime.github.iotags/messages/">messages</a>&nbsp;
                  
                    #<a href="https://systemime.github.iotags/%E5%BC%B9%E7%AA%97/">弹窗</a>&nbsp;
                  
                </span>
              

            </article>
          
            <article class="post-preview">
              <a href="https://systemime.github.io/blog/2019-04/django%E8%8E%B7%E5%8F%96%E6%8C%87%E5%AE%9A%E5%88%97%E7%9A%84%E6%95%B0%E6%8D%AE/">
                <h2 class="post-title">Django获取指定列的数据</h2>

                
              </a>

              <p class="post-meta">
                Posted on April 6, 2019
              </p>
              <div class="post-entry">
                
                  <p>model一般都是有多个属性的，但是很多时候我们又只需要查询特定的某一个，这个时候可以用到<code>values</code>和<code>values_list</code></p>
<h2 id="二者简介">二者简介</h2>
<pre><code>[values()](https://docs.djangoproject.com/en/1.9/ref/models/querysets/#values)
values()¶

values(*fields)¶
Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.

Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.
</code></pre><pre><code>[values_list()](https://docs.djangoproject.com/en/1.9/ref/models/querysets/#values-list)
values_list()¶

values_list(*fields, flat=False)¶
This is similar to values() except that instead of returning dictionaries, it returns tuples when iterated over. Each tuple contains the value from the respective field passed into the values_list() call — so the first item is the first field, etc.
</code></pre><h2 id="values查询">values查询</h2>
<pre><code>from attendence.models import Employee
from attendence.models import EmployeeIP

#获取一个字段
ipList = EmployeeIP.objects.values(&quot;IP&quot;).first()
print(type(ipList))
# &lt;class 'dict'&gt;
print(ipList)
# {'IP': '192.168.1.41'}

#获取多个字段
empList = Employee.objects.values(&quot;first_name&quot;, &quot;last_name&quot;, &quot;email&quot;)[0:2]
print(type(empList))
# &lt;class 'django.db.models.query.QuerySet'&gt;
print(empList)
# [
#   {'last_name': 'Wei', 'first_name': 'Vena', 'email': 'Vena@test.com'},
#   {'last_name': 'Wan', 'first_name': 'Mark', 'email': 'mwan@test.com'}
# ]
</code></pre><h2 id="values_list查询">values_list查询</h2>
<pre><code>ipList = EmployeeIP.objects.values_list(&quot;IP&quot;).first()
print(type(ipList))
# &lt;class 'tuple'&gt;
print(ipList)
# ('192.168.1.111',)

ipList = EmployeeIP.objects.values_list(&quot;IP&quot;)[0:2]
print(type(ipList))
# &lt;class 'django.db.models.query.QuerySet'&gt;
print(ipList)
# [('192.168.1.41',), ('192.168.1.44',)]
print(type(ipList[0]))
# &lt;class 'tuple' &gt;
print(ipList[0])
# 192.168.1.111
</code></pre><h2 id="区别">区别</h2>
<p>从上面的代码中我们可以看到返回结果类型上细微的差别</p>
<ul>
<li>vlaues -
<ul>
<li>单条记录 - <code>&lt;class 'dict'&gt;</code></li>
<li>多条记录 - <code>&lt;class 'django.db.models.query.QuerySet'&gt;</code></li>
</ul>
</li>
<li>vlaues_list -
<ul>
<li>单条记录 - <code>&lt;class 'tuple'&gt;</code></li>
<li>多条记录 - <code>&lt;class 'django.db.models.query.QuerySet'&gt;</code></li>
</ul>
</li>
</ul>

                
              </div>

              
                <span class="post-meta">
                  
                    #<a href="https://systemime.github.iotags/django/">Django</a>&nbsp;
                  
                    #<a href="https://systemime.github.iotags/models/">models</a>&nbsp;
                  
                </span>
              

            </article>
          
            <article class="post-preview">
              <a href="https://systemime.github.io/blog/2019-04/django-%E5%B8%B8%E7%94%A8%E5%91%BD%E4%BB%A4/">
                <h2 class="post-title">Django 常用命令</h2>

                
              </a>

              <p class="post-meta">
                Posted on April 5, 2019
              </p>
              <div class="post-entry">
                
                  <h2 id="一创建新项目">一、创建新项目</h2>
<div class="highlight"><pre class="chroma"><code class="language-python" data-lang="python"><span class="n">django</span><span class="o">-</span><span class="n">admin</span><span class="o">.</span><span class="n">py</span> <span class="n">startproject</span> <span class="n">my_project</span></code></pre></div>
<h2 id="二创建app">二、创建App</h2>
<div class="highlight"><pre class="chroma"><code class="language-python" data-lang="python"><span class="c1"># 在Django项目的根目录下执行</span>
<span class="n">python3</span> <span class="n">manage</span><span class="o">.</span><span class="n">py</span> <span class="n">startapp</span> <span class="n">my_app</span></code></pre></div>
<h2 id="三同步数据库">三、同步数据库</h2>
<pre><code># make new migrations
python3 manage.py makemigrations
 
# apply all migrations
python3 manage.py migrate

</code></pre><h2 id="四启动服务器">四、启动服务器</h2>
<pre><code># run server
python3 manage.py runserver
</code></pre><h2 id="五创建models">五、创建models</h2>
<div class="highlight"><pre class="chroma"><code class="language-python" data-lang="python"><span class="k">class</span> <span class="nc">App1</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
 
    <span class="n">title</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
 
    <span class="n">category</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">,</span> <span class="n">blank</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
 
    <span class="n">date_time</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateTimeField</span><span class="p">(</span><span class="n">auto_now_add</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
 
    <span class="k">def</span> <span class="fm">__unicode__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
 
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">title</span>
 
    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
 
        <span class="n">ordering</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;-date_time&#39;</span><span class="p">]</span>
		</code></pre></div>
<h2 id="六进入django中的交互式shell">六、进入Django中的交互式shell</h2>
<pre><code>python3 manage.py shell
 
from app1.models import App1
 
# create(增加操作)
App1.objects.create(title='title',category='category1')
 
# all和get(查看操作)
App1.objects.all()
App1.objects.get(id=1)
 
# update(修改操作)
demo = App1.objects.get(id=1)
demo.title
demo.title='title2'
 
# delete(删除操作)
demo.delete()
</code></pre><h2 id="七创建一个超级用户">七、创建一个超级用户</h2>
<pre><code>python3 manage.py createsuperuser
 
# 输入http://127.0.0.1:8000/admin登录后台
</code></pre><h2 id="八数据库信息的增加和删除adminpy中增加代码">八、数据库信息的增加和删除，admin.py中增加代码</h2>
<pre><code>from article.models import App1
 
admin.site.register(App1)
</code></pre><h2 id="九将代码上传到github">九、将代码上传到Github</h2>
<pre><code># 在github中新建仓库django-blog
# 在项目根目录下执行
git init
git remote add Django
git@github.com:ybbz/django-blog.git
git add .
git status
git commit -m &quot;django blog init&quot;
git pull Django master &amp;&amp; git push Django master
</code></pre><h2 id="十error-that-port-is-already-in-use">十、Error: That port is already in use.</h2>
<pre><code>ps aux | grep -i manage
kill -9 ****
python3 manage.py runserver
</code></pre>
                
              </div>

              
                <span class="post-meta">
                  
                    #<a href="https://systemime.github.iotags/django/">Django</a>&nbsp;
                  
                    #<a href="https://systemime.github.iotags/%E5%91%BD%E4%BB%A4/">命令</a>&nbsp;
                  
                </span>
              

            </article>
          
        </div>
        
          <ul class="pager main-pager">
            
              <li class="previous">
                <a href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/page/4">&larr; Newer Posts</a>
              </li>
            
            
              <li class="next">
                <a href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/page/6">Older Posts &rarr;</a>
              </li>
            
          </ul>
        
      </div>
    <div align="center" class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
        

<ul class="pagination">
    
    <li class="page-item">
        <a href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/" class="page-link" aria-label="First"><span aria-hidden="true">&laquo;&laquo;</span></a>
    </li>
    
    <li class="page-item">
    <a href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/page/4/" class="page-link" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a>
    </li>
    
    
    
    
    
    
    
        
        
    
    
    <li class="page-item"><a class="page-link" href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/">1</a></li>
    
    
    
    
    
    
        
        
    
    
    <li class="page-item"><a class="page-link" href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/page/2/">2</a></li>
    
    
    
    
    
    
        
        
    
    
    <li class="page-item"><a class="page-link" href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/page/3/">3</a></li>
    
    
    
    
    
    
        
        
    
    
    <li class="page-item"><a class="page-link" href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/page/4/">4</a></li>
    
    
    
    
    
    
        
        
    
    
    <li class="page-item active"><a class="page-link" href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/page/5/">5</a></li>
    
    
    
    
    
    
        
        
    
    
    <li class="page-item"><a class="page-link" href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/page/6/">6</a></li>
    
    
    
    
    
    
        
        
    
    
    <li class="page-item disabled"><span aria-hidden="true">&nbsp;&hellip;&nbsp;</span></li>
    
    
    
    
    
    
        
        
    
    
    
    
    
    
    
        
        
    
    
    
    
    
    
    
        
        
    
    
    
    
    
    
    
        
        
    
    
    <li class="page-item"><a class="page-link" href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/page/11/">11</a></li>
    
    
    <li class="page-item">
    <a href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/page/6/" class="page-link" aria-label="Next"><span aria-hidden="true">&raquo;</span></a>
    </li>
    
    <li class="page-item">
        <a href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/page/11/" class="page-link" aria-label="Last"><span aria-hidden="true">&raquo;&raquo;</span></a>
    </li>
    
</ul>


        
        
        
        
        
      </div>
    </div>
  </div>

    <div class="rocket"><img src="https://systemime.github.io/img/rocket_up.png" alt="" width="100" height="100"></div>
<script>
    $(function () {
      $(window).scroll(function () {
        
        if ($(window).scrollTop() >= 1000) {
          $('.rocket').stop().fadeIn(1000);
        }else {
          $('.rocket').stop().fadeOut(1000);
        }
      })
      
      $('.rocket').click(function () {
        $('html,body').stop().animate({scrollTop:0},400);
       
      })
    })

</script>

    
    <div id="landlord">
        <div class="message" style="opacity:0"></div>
        <canvas id="live2d" width="280" height="250" class="live2d"></canvas>
        <div class="hide-button">隐藏</div>
    </div>
    
    <footer id="copyright">
  <div class="container">
    <div class="row">
      <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
        <ul class="list-inline text-center footer-links">
          
          
        </ul>
        <p class="credits copyright text-muted">
        &copy;2017-2018
          
          &nbsp;&bull;&nbsp;
          September 20,2019
          updated
          
            &nbsp;&bull;&nbsp;
            <a href="https://systemime.github.io">Home</a>
          
        </p>

        <p class="credits theme-by text-muted">
        <a href="https://servicemesher.github.io" target="_blank">ServiceMesher</a>&nbsp;&bull;&nbsp;<a href="https://github.com/yangchuansheng/k8s-knowledge" target="_blank">Kubernetes 知识图谱</a>
        <br />
        <span id="busuanzi_container_site_pv">
            本站已被访问 <span id="busuanzi_value_site_pv"></span> 次啦
        </span>
        <span id="busuanzi_container_site_uv">
            &ensp;|&ensp;&thinsp;您是第 <span id="busuanzi_value_site_uv"></span> 位到访的小伙伴喔
        </span>
        </p>
        
        <p class="credits theme-by text-muted">
          <a href="http://gohugo.io">Hugo v0.67.0</a> powered &nbsp;&bull;&nbsp; Theme by <a href="http://deanattali.com/beautiful-jekyll/">Beautiful Jekyll</a> adapted to <a href="https://github.com/halogenica/beautifulhugo">Beautiful Hugo</a>
          
          <center><section class="credits theme-by text-muted">
    <span class="footer__copyright">
    <div>
    <span id="span_dt_dt"> </span>
    <script language="javascript">
      function show_date_time(){
        window.setTimeout("show_date_time()", 1000);
        BirthDay=new Date("7/8/2017 10:56:12");
        today=new Date();
        timeold=(today.getTime()-BirthDay.getTime());
        sectimeold=timeold/1000
        secondsold=Math.floor(sectimeold);
        msPerDay=24*60*60*1000
        e_daysold=timeold/msPerDay
        daysold=Math.floor(e_daysold);
        e_hrsold=(e_daysold-daysold)*24;
        hrsold=Math.floor(e_hrsold);
        e_minsold=(e_hrsold-hrsold)*60;
        minsold=Math.floor((e_hrsold-hrsold)*60);
        seconds=Math.floor((e_minsold-minsold)*60);
        span_dt_dt.innerHTML="本博客已经开心运行 "+daysold+" 天 "+hrsold+" 小时 "+minsold+" 分 "+seconds+" 秒";
      }
      show_date_time();
    </script>
    </div>
</script>
</section>
</center>
        </p>
      </div>
    </div>
  </div>
</footer>


<script src="https://res.cloudinary.com/jimmysong/raw/upload/rootsongjc-hugo/bootstrap.min.js"></script>
<script src="https://res.cloudinary.com/jimmysong/raw/upload/rootsongjc-hugo/photoswipe-ui-default.min.js"></script>
<script src="https://res.cloudinary.com/jimmysong/raw/upload/rootsongjc-hugo/photoswipe.min.js"></script>
<script src="https://res.cloudinary.com/jimmysong/raw/upload/rootsongjc-hugo/auto-render.min.js"></script>
<script src="https://systemime.github.io/js/main.js"></script>
<script src="https://systemime.github.io/js/clipboard.min.js"></script>
<script src="https://systemime.github.io/js/prism.js?t=123"></script>
<script src="https://systemime.github.io/js/highlight.min.js"></script>
<script src="https://res.cloudinary.com/jimmysong/raw/upload/rootsongjc-hugo/katex.min.js"></script>
<script src="https://systemime.github.io/js/reward.js"></script>
<script src="https://systemime.github.io/js/canvas_ribbon.js"></script>
<script> renderMathInElement(document.body); </script>

<script src="https://systemime.github.io/js/baguetteBox.js"></script>
<script> baguetteBox.run('.gallery');</script>






<script async defer src="https://buttons.github.io/buttons.js"></script>


<script src="https://polyfill.io/v2/polyfill.min.js?features=IntersectionObserver"></script>
<script type="text/javascript" src="https://systemime.github.io/js/quicklink.umd.js"></script>
<script>
window.addEventListener('load', () =>{
   quicklink();
});
</script>



<script type="text/javascript">
 
var a_idx = 0;
jQuery(document).ready(function($) {
    $("body").click(function(e) {
        var a = new Array("Docker", "Kubernetes", "Prometheus", "Envoy", "Istio", "Service Mesh", "Cloud Native");
        var $i = $("<span />").text(a[a_idx]);
        a_idx = (a_idx + 1) % a.length;
        var x = e.pageX,
        y = e.pageY;
        function randomColor() {
          var flakeColor = new Array("#FFDA65", "#00BFFF", "#BA55D3", "#FFA07A", "#87CEEB", "#FFB6C1");
          var snowColor = flakeColor[Math.floor(flakeColor.length * Math.random())];
          return snowColor;
        }
        $i.css({
            "z-index": 999999999999999999999999999999999999999999999999999999999999999999999,
            "top": y - 20,
            "left": x,
            "position": "absolute",
            "font-weight": "bold",
            "color": randomColor()
        });
        $("body").append($i);
        $i.animate({
            "top": y - 180,
            "opacity": 0
        },
        1500,
        function() {
            $i.remove();
        });
    });
});
</script>


<script type="text/javascript" src="https://systemime.github.io/js/lightbox.js"></script>











<script src="https://cdn.plyr.io/3.4.7/plyr.js"></script>
<script>const player = new Plyr('#player');</script>


<script async defer src="https://buttons.github.io/buttons.js"></script>


  </body>
</html>

